package com.my12306.train.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my12306.common.constant.CommonConstants;
import com.my12306.common.enums.CodeEnum;
import com.my12306.common.model.vo.PageVo;
import com.my12306.common.util.PageUtils;
import com.my12306.common.util.SnowflakeIdWorker;
import com.my12306.common.util.response.ResponseData;
import com.my12306.train.constant.TrainConstant;
import com.my12306.train.dao.OrderDao;
import com.my12306.train.model.entity.CarriageEntity;
import com.my12306.train.model.entity.OrderEntity;
import com.my12306.train.model.entity.SeatEntity;
import com.my12306.train.model.entity.TicketEntity;
import com.my12306.train.model.vo.OrderUserVo;
import com.my12306.train.model.vo.OrderVo;
import com.my12306.train.service.CarriageService;
import com.my12306.train.service.OrderService;
import com.my12306.train.service.SeatService;
import com.my12306.train.service.TicketService;
import com.my12306.user.model.po.PUserEntity;
import com.my12306.user.service.PUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private TicketService ticketService;
    @Resource
    private SeatService seatService;
    @Resource
    private PUserService pUserService;
    @Resource
    private CarriageService carriageService;
    @Override
    public PageUtils queryOrderPage(PageVo pageVo) {
        pageVo = pageVo.init();
        List<OrderEntity> orderEntities = this.baseMapper.queryOrderPage(pageVo, CommonConstants.LogicDelete.no_delet.getValue());
        if(orderEntities != null){
            Integer dataCount = queryOrderCount(pageVo, CommonConstants.LogicDelete.no_delet.getValue());
            System.out.println("数据总量：" + dataCount);
            return PageUtils.build(pageVo, orderEntities, dataCount);
        }
        return null;
    }

    @Override
    public Integer queryOrderCount(PageVo pageVo, int logicDelete) {
        Integer count = this.baseMapper.queryOrderCount(pageVo, logicDelete);
        return count;
    }

    @Override
    @Transactional
    public ResponseData deleteOrderBatchByIds(List<Long> orderIds) {
        this.baseMapper.deleteOrderBatchByIds(orderIds, CommonConstants.LogicDelete.delete.getValue());
        return ResponseData.ok();
    }

    @Override
    @Transactional
    public ResponseData saveTicket(OrderVo orderVo) {

        List<String>trainCodes = new ArrayList<>();
        trainCodes.add(orderVo.getTrainCode());
        //找出起始站开始未销售的席位
        List<SeatEntity> seatEntities = this.seatService.queryTicketSeateByStartDateAndTrainCode(orderVo.getStartDate(), trainCodes, TrainConstant.SEATE_NOT_SOLD, orderVo.getStartStation(), CommonConstants.LogicDelete.no_delet.getValue());
        AtomicReference<SeatEntity> atoSeatEntity= new AtomicReference<>(null);
        List<CarriageEntity> carriageEntities = this.carriageService.queryAllCarriageByTrainCode(orderVo.getTrainCode(),CommonConstants.LogicDelete.no_delet.getValue());
        log.error("========>所以车厢："+carriageEntities);
        List<CarriageEntity> needCarriage = carriageEntities.stream().filter(item -> {
            return item.getCoachSitType().equals((orderVo.getCoachSitType()));
        }).distinct().collect(Collectors.toList());
        CarriageEntity carriageEntity = null;
        //找到用户需要的车厢
        if (needCarriage!=null&&needCarriage.size()>0){
            carriageEntity = needCarriage.get(0);
        }
        if (carriageEntity==null){
            return ResponseData.fail(CodeEnum.FAIL.getCode(),"支付失败！，请重新选择席位！");
        }
        log.error("==========>所有席位："+seatEntities);
        //找出席位
        if (seatEntities!=null&&seatEntities.size()>0){
            CarriageEntity finalCarriageEntity = carriageEntity;
            //查找出该类型的席位选择一个
            List<SeatEntity> seatNeedList = seatEntities.stream().filter(item -> {
                return item.getCoachNumber().equals(finalCarriageEntity.getCoachNumber());
            }).collect(Collectors.toList());

            log.error("==================>用户购买类型的席位："+seatNeedList);
            if (seatNeedList!=null&&seatNeedList.size()>0){
                seatNeedList.stream().forEach(x->{
                    atoSeatEntity.set(x);
                });
            }else{
                log.error("====>找不到剩余的准备找已经购票但不影响当前购票的席位");
                //找出所有该起始站之前所有的站，然后找出已经被购票但是没影响当前购票
                List<String> stations = ticketService.getStationByStation(orderVo.getFromId(), orderVo.getTrainCode());
                if (stations!=null&&stations.size()>0) {
                    List<SeatEntity> seatList = this.seatService.queryTicketSeate(orderVo.getStartDate(), orderVo.getTrainCode(), stations, TrainConstant.SEATE_SOLD, CommonConstants.LogicDelete.no_delet.getValue());
                    log.error("===>所以已经购票但还允许当前用户购票的席位"+seatList);
                    if (seatList!=null&&seatList.size()>0){
                        seatList.stream().forEach(x->{
                            atoSeatEntity.set(x);
                        });

                    }
                }
            }
        }
        SeatEntity seatEntity = atoSeatEntity.get();

        //如果等于null 证明席位被抢了
        if (seatEntity==null){
            return ResponseData.fail(CodeEnum.ADD_FAIL.getCode(),"购买票失败！,原因：车票已经被抢购完！");
        }

        //1.添加用户订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId(SnowflakeIdWorker.generateId());
        orderEntity.setOrderDate(new Date());
        orderEntity.setCreateDate(new Date());
        orderEntity.setUpdateDate(new Date());
        orderEntity.setUserId(orderVo.getUserId());
        orderEntity.setOrderStatus(1);
        Double prices = orderVo.getPrices();
        BigDecimal bigDecimal = new BigDecimal(prices);
        orderEntity.setOrderMoney(bigDecimal);
        orderEntity.setSeatId(seatEntity.getSeatId());
        this.save(orderEntity);
        //2.添加系统的
        TicketEntity ticketEntity = new TicketEntity();
        ticketEntity.setCoachNo(seatEntity.getCoachNumber());
        ticketEntity.setCreateDate(new Date());
        ticketEntity.setEndStation(orderVo.getEndStation());
        ticketEntity.setStartStation(orderVo.getStartStation());
        ticketEntity.setIdCard(orderVo.getIdCard());
        ticketEntity.setPassengerName(orderVo.getRealName());
        ticketEntity.setPassengerType(orderVo.getTicketType());
        ticketEntity.setPrice(orderVo.getPrices());
        ticketEntity.setSaleDate(new Date());
        ticketEntity.setSeatNo(seatEntity.getSeatNo());
        ticketEntity.setTrainCode(orderVo.getTrainCode());
        ticketEntity.setSaleMethod("网上购票");
        ticketEntity.setSaleMethodDetail("12306app买票");
        this.ticketService.save(ticketEntity);
        //3.修改状态
        seatEntity.setStartStation(orderVo.getStartStation());
        seatEntity.setEndStation(orderVo.getEndStation());
        seatEntity.setSeatStatus(TrainConstant.SEATE_SOLD);
        this.seatService.updateSeatById(seatEntity);
        return ResponseData.ok();
    }

    @Override
    public PageUtils queryUserOrderPage(PageVo pageVo) {
        pageVo = pageVo.init();
        List<OrderUserVo> orderEntities = this.baseMapper.queryUserOrderPage(pageVo, CommonConstants.LogicDelete.no_delet.getValue());
        if(orderEntities != null){
            PUserEntity pUserEntity = this.pUserService.queryUserById(pageVo.getUserId());
            if (pUserEntity!=null) {
                String idCard = pUserEntity.getIdCard();
                String realname = pUserEntity.getRealname();
                @NotNull String phone = pUserEntity.getPhone();
                orderEntities = orderEntities.stream().map(x -> {
                    if (idCard!=null)
                    x.setIdCard(idCard);
                    if (realname!=null){
                        x.setRealName(realname);
                    }
                    if (phone!=null){
                        x.setPhone(phone);
                    }
                    return x;
                }).distinct().collect(Collectors.toList());
            }
            Integer dataCount = this.baseMapper.queryUserOrderPageCount(pageVo, CommonConstants.LogicDelete.no_delet.getValue());
            System.out.println("数据总量：" + dataCount);
            return PageUtils.build(pageVo, orderEntities, dataCount);
        }
        return null;
    }
}
